/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 8, 2012  4:54:42 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : promis.tested
 * File Name : ReflectionTest.java
 * TODO
 */
package promis.tested;

import java.lang.*;
import java.lang.reflect.*;

import org.apache.log4j.Logger;

/**
 * @author chatree
 *
 */
public class ReflectionTest {	
	private static final Logger log = Logger.getLogger(ReflectionTest.class);
	private float f;
	private double d;
	private String s;
	
	public void setValue(String fieldName, Object fieldValue) throws NoSuchFieldException, IllegalAccessException
	{
		Field fields[] = this.getClass().getDeclaredFields();
		int fieldCount = fields.length;
		int i = 0;
		while( i<fieldCount ){
			Field field = fields[i];
			if( field.getName().equals(fieldName) )
				try{
					field.set(this,fieldValue);
				}
				catch(IllegalAccessException iae)
				{
					boolean isAccessible = field.isAccessible();
					if(!isAccessible){
						System.out.println("Changing access modifiers on field : " + field.getName() );
						field.setAccessible(true);
					}
					field.set(this,fieldValue);
				}
			i++;
		}
	} 

	public Class getType(String fieldName) throws NoSuchFieldException
	{
		return getClass().getField(fieldName).getType();
	}

	public int getFieldCount()
	{
		return getClass().getDeclaredFields().length;
	}

	public void showAllFields()
	{
		log.info("showAllFields --- Start");
		Field fields[] =this.getClass().getDeclaredFields();		
		log.info("fields.length : " + fields.length);
		
		for (int index = 0; index < fields.length; index++)
		{
			String output = "Field - name: " + fields[index].getName() + " - value: ";
			try
			{
				if (fields[index].getType().isInstance(Double.TYPE))
					output += String.valueOf(fields[index].getDouble(this));
				else
					if (fields[index].getType().isInstance(Float.TYPE))
						output += String.valueOf(fields[index].getFloat(this));
					else
						output += String.valueOf(fields[index].get(this));
				System.out.println(output);
				}
			catch(IllegalAccessException e)
			{
				log.error(e.getMessage());
				System.err.println(e.getMessage());
			}
		}
		log.info("showAllFields --- End");
	}

	public static void main(String args[])
	{
		ReflectionTest obj = new ReflectionTest();
	
		try
		{
			obj.setValue("f", new Float((float) 0.86));
			obj.setValue("d", new Double(1.6742));
			obj.setValue("s", "Whatever");
		
			System.out.println(obj.getFieldCount());
			
			obj.showAllFields();
		}
		catch(NoSuchFieldException e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
		catch(IllegalAccessException e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
}
